package org.jsola.contract.common;

import lombok.Data;
import org.apache.commons.lang3.builder.ToStringBuilder;

import java.io.Serializable;

/**
 * 返回对象
 * @author luopeng
 *
 */
@Data
public class ResultInfo<T> implements Serializable {

	private static final long serialVersionUID = -1L;

	private boolean success; // 操作是否成功
	private String msg; // 操作失败的原因

	private String resultCode;//返回码
	
	private T data;//返回对象
	
	/**异常对象不作序列化传输*/
	private transient Exception exception;//异常对象
	
	public ResultInfo(){}

	public static <T> ResultInfo<T> create(Class<T> cls){
		return new ResultInfo<T>();
	}
	
	public static ResultInfo<Void> create(){
		return new ResultInfo<Void>();
	}
	
	public static ResultInfo<Void> createFail(Exception e){
		ResultInfo<Void> result = new ResultInfo<Void>();
		result.fail(e);
		return result;
	}
	
	public static ResultInfo<Void> createFail(String msg,Exception e){
		ResultInfo<Void> result = new ResultInfo<Void>();
		result.fail(msg,e);
		return result;
	}
	
	public ResultInfo<T> success(){
		this.success = true;
		return this;
	}
	
	public ResultInfo<T> success(T data){
		this.success = true;
		this.data = data;
		return this;
	}
	
	public ResultInfo<T> fail(){
		this.success = false;
		return this;
	}
	
	public ResultInfo<T> fail(String msg){
		this.success = false;
		this.msg = msg;
		return this;
	}
	
	public ResultInfo<T> fail(Exception e){
		this.success = false;
		if(e != null){
			this.exception = e;
			this.msg = e.getMessage();
		}
		return this;
	}
	
	public ResultInfo<T> fail(String msg,Exception e){
		this.success = false;
		this.msg = msg;
		if(e != null){
			this.exception = e;
		}
		return this;
	}

	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}
}
